<?php

if (!isset($_POST['username']) || !isset($_POST['password'])) {
  echo 'Invalidate sign request';
  return;
}

$username = $_POST['username'];
$password = $_POST['password'];

if (preg_match('/^[0-9a-zA-Z]+@[0-9a-zA-Z]+\.[a-zA-Z]+$/', $username) != 1) {
  echo 'Invalidate username, please input email';
  return;
}

//if (!(strlen($password) >= 6 && strlen($password) <= 12))
if (strlen($password) < 6 || strlen($password) > 12) {
  echo 'Invalidate password, must be 6-12 characters';
  return;
}

$mysqli = new mysqli('localhost', 'blog-admin', 'blog-admin', 'blog');
if ($mysqli->connect_errno) {
  echo 'Failed to connect to MySQL: (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error;
  return;
}

$sql = 'SELECT * FROM users where username="' . $username . '" and password="' . $password . '"';
$result = $mysqli->query($sql);
if (!$result) {
  echo 'Failed to query: ' . $mysqli->error;
  return;
}

if ($result->num_rows > 0) {
  echo <<<eof
<script type="text/javascript">
  alert('input username already signed up, please use new one');
</script>
eof;
  $result->close();
  return;
}

$sql = 'INSERT INTO users(username, password) VALUES("' . $username . '", "' . $password . '")';
if (!$mysqli->query($sql)) {
  echo 'Failed to sign up: ' . $mysqli->error;
  return;
}

$mysqli->close();

echo <<<eof
  <script type='text/javascript'>
  window.location = '/index.html';
  </script>
eof;
